package com.lzy.chat.f_config;

import com.lzy.chat.a_entity.User;
import com.lzy.chat.g_annotation.CurrentUser;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

//CurrentUser注解实现类
public class CurrentUserHandlerMethodArgResolver implements HandlerMethodArgumentResolver {
    /**
     * 判断是否支持使用@CurrentUser注解的参数
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(CurrentUser.class) != null && parameter.getParameterType() == User.class;
    }

    /**
     * 注入参数值
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        //取得HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        //取出session中的User
        return request.getSession().getAttribute("currentUser");
    }
}
